<template>
  <router-link to="/editor">Go to Editor</router-link>
  <el-table :data="dirList" table-layout="auto">
    <el-table-column prop="id" label="id" />
    <el-table-column prop="title" label="标题" />
    <el-table-column prop="path" label="主图">
      <template #default="{ row }">
        <!-- <router-link :to="{path:'/editor',query:{id:row.id}}"></router-link> -->
        <el-image  v-if="row.path" :src="row.path" fit="contain" style="width: 100%;max-width: 150px;max-height: 150px;"  @click="setThumbnail(row)" />
        <el-button v-else type="primary" @click="setThumbnail(row)"> 设置主图</el-button>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="right">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑文章</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="centerDialogVisible" title="插入图片" append-to-body fullscreen center top='0px' class="file-dialog">
    <FilesPage ref="filesPageRef" :config-option="configOption"></FilesPage>
    <el-button @click="getImage" type="primary">
      插入图片
    </el-button>
    <el-button @click="centerDialogVisible = false">
      取消
    </el-button>

  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, onUnmounted } from 'vue';
import FilesPage from '@/pages/files/index.vue';
import { createThumbnail, createImageUrl } from "@/utils/image.js";

import { useRouter, useRoute } from 'vue-router';
const router = useRouter();

import { storeToRefs } from "pinia";
import useDirStore from "@/stores/dir";
const dirStore = useDirStore();
const { dirList } = storeToRefs(dirStore);

//文件插入对话框选项及refs
const configOption = reactive({ hasClose: true, hasUpload: false });
const filesPageRef = ref();
// 对话框打开
const centerDialogVisible = ref(false);
//正在设置主图的文章ID
const articleId = ref(0)
//开始设置主图
function setThumbnail(row) {
  centerDialogVisible.value = true;
  const id = row.id * 1
  articleId.value = id
  nextTick().then(() => {
    filesPageRef.value.setClickDirID(id);
  })
}
//选择主图 无论选多少张图，只会设置第二张为主图
function getImage() {
  const arr = filesPageRef.value.getSelected();
  centerDialogVisible.value = false;
  const id = articleId.value;
  if(arr[0] && arr[0]){
    dirStore.setArticleImage(id,arr[0])
  }
}
//编辑文章
function handleEdit(index, row) {
  router.push({ path: '/editor', query: { dirId: row.id,path:row.path } })
}
</script>
<style scoped ></style>